<?php

// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );
jimport('joomla.application.component.controller');
jimport('joomla.user.helper');

class WrdControllerProfile extends JControllerLegacy
{
    public function __construct($cfg = array()) {
       
		parent::__construct($cfg);
        $mainframe = JFactory::getApplication();
    }
   
    public function activate($data = array())
    {
        
		$user       = JFactory::getUser();
        $uParams    = JComponentHelper::getParams('com_users');
       
        // If the user is logged in, return them back to the homepage.
        if ($user->get('id')) {
            $this->setRedirect('index.php');
            return true;
        }

        // If user registration or account activation is disabled, throw a 403.
        if ($uParams->get('useractivation') == 0 || $uParams->get('allowUserRegistration') == 0) {
            JError::raiseError(403, JText::_('JLIB_APPLICATION_ERROR_ACCESS_FORBIDDEN'));
            return false;
        }
		
		
        $model = $this->getModel('profile', 'WrdModel');
		
        $token = JRequest::getVar('token', null, 'request', 'alnum');

        // Check that the token is in a valid format.
        if ($token === null || strlen($token) !== 32) {
            JError::raiseError(403, JText::_('JINVALID_TOKEN'));
            return false;
        }
        
		$memberid = $this->generateMemberId();
		$tmp_pass = JRequest::getVar('key');
		
        // Attempt to activate the user.
        $return = $model->activate($token,$memberid);
		
		$profile = WrdHelper::getUserProfile($memberid,'member_id');
		WrdHelper::updatePointOfUser($profile->user_id,$profile->member_id,$profile->dob,$profile->f_name,$profile->l_name);
        
		//send email for admin
		$this->sendMailNotice($memberid,$profile->id);
		
		// Check for errors.
        if ($return === false) {
        	
            // Redirect back to the homepage.
            $this->setMessage(JText::sprintf('COM_USERS_REGISTRATION_SAVE_FAILED', $model->getError()), 'warning');
            $this->setRedirect('index.php');
            return false;
        }
        else{
        	//login
			JRequest::setVar('username',$memberid);
        	JRequest::setVar('password',$tmp_pass,'post');
        	
        	$this->login();
        }

        $useractivation = $uParams->get('useractivation');
        
        // Redirect to the login screen.
        if ($useractivation == 0)
        {
            $this->setMessage(JText::_('COM_USERS_REGISTRATION_SAVE_SUCCESS'));
            $this->setRedirect(JRoute::_(WrdHelperRoute::getProfileLoginRoute(), false));
        }
        else if ($useractivation == 1)
        {
            $this->setMessage(JText::_('COM_USERS_REGISTRATION_ACTIVATE_SUCCESS'));
            $this->setRedirect(JRoute::_(WrdHelperRoute::getProfileLoginRoute(), false));
        }
        else if ($return->getParam('activate'))
        {
            $this->setMessage(JText::_('COM_USERS_REGISTRATION_VERIFY_SUCCESS'));
            $this->setRedirect(JRoute::_(WrdHelperRoute::getProfileLoginRoute(), false));
        }
        else
        {
            $this->setMessage(JText::_('COM_USERS_REGISTRATION_ADMINACTIVATE_SUCCESS'));
            $this->setRedirect(JRoute::_(WrdHelperRoute::getProfileLoginRoute(), false));
        }
        return true;
    }
    
	
	function sendMailNotice($memberid,$id){
    	
		$db = &JFactory::getDbo();

		//get email template
		$sql = 'SELECT * FROM #__wrd_cemail WHERE `action` = "registration" AND type = "admin"';
		$db->setQuery($sql) ;
		$rs = $db->loadObject();

		if(!empty($rs)){
		
			$profile_link = '<a href="'.JURI::base().'administrator/index.php?option=com_wrd&controller=profile&id='.$id.'&layout=form">'.$memberid.'</a>';
			$emailBody = $rs->template ;
			$emailBody = str_replace('{line-break}', '<br />', $emailBody);
			$emailBody = str_replace('{memberid}',$profile_link, $emailBody);
			$emailBody = str_replace('{link}', $profile_link, $emailBody);
			
			$emailBody = wordwrap($emailBody, 70);

			$emailSubject = $rs->subject;
			$mailFrom = 'info@wmcvip.vn';
            $toemail = explode(',', $rs->email);
			JUtility::sendMail($mailFrom, $rs->name, $toemail, $emailSubject, $emailBody,1);
		}
		
    }
    /**
     * Save Registration steps 
     */
    public function save(){
      
        /******* Check Access *******/
        JRequest::checkToken() or jexit(JText::_('JINVALID_TOKEN'));        
        
        /******* Pre Init *******/
        $db = JFactory::getDbo();
        $mainframe = JFactory::getApplication();
        $user = JFactory::getUser();
        $profileModel = JModelLegacy::getInstance('Profile', 'WrdModel');
        $userProfile = $profileModel->checkStepRegistration($user->id);
        $post = $_POST;
		
		//Send email notification when change field of profile member
        $this->sendEmailNoticeWhenUserChangeProfile($post);
        
		/******** Process post data ********/
        $obj = new stdClass();
        $obj->id = $userProfile->id;
        $obj->user_id = $userProfile->user_id;
      
        if($user->id != 0) {
            $stepLink = self::checkCurrentStep($post);
			
            $userProfile->stepLink = $stepLink;
			
            if($userProfile->step == 1 || $stepLink == 1) {
				$this->updateStepOne($obj, $post, $profileModel, $userProfile);
				//$this->sendEmailNoticeWhenUserChangeProfile($post);
                if($post['continue'] == 1)
                	$mainframe->redirect(WrdHelperRoute::getProfileRoute(2));
                else 
                	$mainframe->redirect(WrdHelperRoute::getMyProfileRoute());
            }
            
            else if($userProfile->step == 2 || $stepLink == 2) {
            	
                self::updateStepTwo($obj, $post, $profileModel, $userProfile);
				//$this->sendEmailNoticeWhenUserChangeProfile($post);
                if($post['continue'] == 1)
					$mainframe->redirect(WrdHelperRoute::getProfileRoute(3));
                else 
					$mainframe->redirect(WrdHelperRoute::getMyProfileRoute()); 
            }
                    
            else if($userProfile->step == 3 || $stepLink == 3) {
            	
                self::updateStepThree($obj, $post, $profileModel, $userProfile);
				//$this->sendEmailNoticeWhenUserChangeProfile($post);
                if($post['continue'] == 1)
               		$mainframe->redirect(WrdHelperRoute::getProfileRoute(4)); 
                else
                	$mainframe->redirect(WrdHelperRoute::getMyProfileRoute());
            }
            
            else if($userProfile->step == 4 || $stepLink == 4) {
                self::updateStepFour($obj, $post, $profileModel, $userProfile);
				//$this->sendEmailNoticeWhenUserChangeProfile($post);
				//$mainframe->redirect(WrdHelperRoute::getMyProfileRoute());
				$lang =& JFactory::getLanguage();
	        	if($lang->getTag() == 'vi-VN')
	        		$mainframe->redirect('index.php?option=com_content&view=article&id=222&Itemid=232&lang=vi');
	        	else 
	        		$mainframe->redirect('index.php?option=com_content&view=article&id=221&Itemid=231&lang=en');
			}
						
        }
        else { // Register
            self::registerNewAccount();
        }        
    }
    
    private function updateStepOne(&$obj, $post, $profileModel, $userProfile){
    	
		$user = &JFactory::getUser();
    	$app = &JFactory::getApplication('site');
		$db = &JFactory::getDBO();
		
    	if($user->id == 0)
    		$app->redirect('index.php#login');
    	
        $obj->prefix = $post['prefix'];
        $obj->step = ($userProfile->step < 2 ? 2 : $userProfile->step);

        if(isset($post['year_birth'])&& isset($post['month_birth']) && isset($post['day_birth'] )){
            $obj->dob = intval($post['year_birth']).'-'.intval($post['month_birth']).'-'.intval($post['day_birth']);
		}
        
        $obj->step_link = $userProfile->stepLink;
        $obj->f_name = $post['f_name'];
        $obj->l_name = $post['l_name'];
        $obj->name_on_card = $post['name_on_card'];       
        $obj->nationality = $post['nationality'];
        $obj->p_email = $post['p_email'];
       	if($user->profile->p_email != $post['p_email']){
			//check email
			if(WrdHelper::isEmail($post['p_email']) == true){
				$query = 'SELECT email FROM #__users WHERE email ="'.$post['p_email'].'"';
				$rs = $db->setQuery($query)->loadObject()->email;
				if($rs != '')
				{
					$app->redirect(WrdHelperRoute::getProfileRoute(1),'Double Email');
				}
			}
			else{
				$app->redirect(WrdHelperRoute::getProfileRoute(1),'Wrong Email');
			}
		}
		
        $obj->alternative_email = $post['alternative_email'];
        $obj->country_code = $post['country_code'];
        $obj->phone = $post['phone'];
        $obj->address = $post['address'];
        $obj->country = $post['country'];
        
        $obj->city = $post['city'];
        $obj->distric = $post['distric'];
        $obj->pick_up_at = $post['pick_up_at'];
        $obj->lprefer = $post['lprefer'];
        $obj->referer = $post['referer'];            
        $obj->referer_phone = $post['referer_phone'];

        
        if($post['prefix'] == 'Prof.' || $post['prefix'] == 'Dr.' || $post['prefix'] == 'Mr.')
        	$obj->gender = 'male' ;
        else
        	$obj->gender = 'female' ;

        
        $profileModel->updateStepRegistration($obj);
        $this->updateSystemUser($post);
		WrdHelper::updateSummaryPoint($user->id,date('Y'),date('m'));
        
		$profile = WrdHelper::getUserProfile($user->id,'userid');
		
		$myPoint = WrdHelper::updatePointOfUser($profile->user_id,$profile->member_id,$profile->dob,$profile->f_name,$profile->l_name);
        
        $_SESSION[$user->id.'p'] = $myPoint;
    }

	public function updateSystemUser($post){
		$db = &JFactory::getDBO();
		$user = &JFactory::getUser();
		
		$tmp_obj = new stdClass();
		$tmp_obj->id = $user->id;
		$tmp_obj->name = $post['f_name'].' '.$post['l_name'];
		$tmp_obj->email = $post['p_email'];
		
		$db->updateObject('#__users',$tmp_obj,'id');
	}
    
    private function updateStepTwo(&$obj, $post, $profileModel, $userProfile)
    {
    	
    	$user = &JFactory::getUser();
    	$app = &JFactory::getApplication('site');
    	if($user->id == 0)
    		$app->redirect('index.php#login');
    	
        $obj->status = $post['status'];
        $obj->step = ($userProfile->step < 3 ? 3 : $userProfile->step);
        $obj->step_link = $userProfile->stepLink;
        
        /**** social ****/
        if(!empty($post['social'])){
            $obj->social = array();
            foreach($post['social'] as $item) {
                $obj->social[$item] = $item;
            }
            $obj->social = serialize($obj->social);
        } else {
            $obj->social = '';
        }
        
        $obj->website = $post['website'];
        $obj->skype = $post['skype'];
        $obj->yahoo = $post['yahoo'];       
        $obj->gtalk = $post['gtalk'];
        $obj->msn = $post['msn'];
        $obj->facebook = $post['facebook'];
        
        /**** Hobbies ****/
        if(!empty($post['hobbies'])){
            $obj->hobbies = array();
            foreach($post['hobbies'] as $item) {
                $obj->hobbies[$item] = $item;
            }
            $obj->hobbies = serialize($obj->hobbies);
        } else {
            $obj->hobbies = '';
        }
        
        $obj->other_hobbies = $post['other_hobbies'];
        $obj->own_car = $post['own_car'];
        $obj->num_children = $post['num_children'];
        $obj->o_a_weekend = $post['o_a_weekend'];
        /**** weekend_action ****/
        if(!empty($post['weekend_action'])){
            $obj->weekend_action = array();
            foreach($post['weekend_action'] as $item) {
                $obj->weekend_action[$item] = $item;
            }
            $obj->weekend_action = serialize($obj->weekend_action);
        } else {
            $obj->weekend_action = '';
        }
             
        $profileModel->updateStepRegistration($obj);
        
		WrdHelper::updateSummaryPoint($user->id,date('Y'),date('m'));
        
		$profile =  WrdHelper::getUserProfile($user->id,'userid');
		$myPoint = WrdHelper::updatePointOfUser($profile->user_id,$profile->member_id,$profile->dob,$profile->f_name,$profile->l_name);
        
        $_SESSION[$user->id.'p'] = $myPoint;
    }
    
    private function updateStepThree(&$obj, $post, $profileModel, $userProfile){
    	
    	$user = &JFactory::getUser();
    	$app = &JFactory::getApplication('site');
    	if($user->id == 0)
    		$app->redirect('index.php#login');
    	
        $obj->job_prefix = $post['job_prefix'];
        $obj->step = ($userProfile->step < 4 ? 4 : $userProfile->step);
        $obj->step_link = $userProfile->stepLink;
        
        $obj->job = $post['job'];
        $obj->o_job = $post['o_job'];
        $obj->department = $post['department'];       
        $obj->company_name = $post['company_name'];
        $obj->industry = $post['industry'];
        
        
        $obj->c_info = $post['c_info'];
        $obj->c_addr = $post['c_addr'];
        $obj->c_country = $post['c_country'];
        $obj->c_city = $post['c_city'];
        $obj->c_distric = $post['c_distric'];
        $obj->o_industry = $post['o_industry'];
        $obj->o_job_prefix = $post['o_job_prefix'];
        
        $this->checkCompany($post['company_name']);
        
        $profileModel->updateStepRegistration($obj);
        WrdHelper::updateSummaryPoint($user->id,date('Y'),date('m'));
        $profile =  WrdHelper::getUserProfile($user->id,'userid');
		$myPoint = WrdHelper::updatePointOfUser($profile->user_id,$profile->member_id,$profile->dob,$profile->f_name,$profile->l_name);
        
        $_SESSION[$user->id.'p'] = $myPoint;
    }
    
    private function updateStepFour(&$obj, $post, $profileModel, $userProfile){
        $user = &JFactory::getUser();
        $app = &JFactory::getApplication('site');
        if($user->id == 0)
        	$app->redirect('index.php#login');
        
        $obj->education = $post['education'];
        $obj->step = 5;
        $obj->step_link = $userProfile->stepLink;
        
        /**** Other Membership Club ****/
        if(!empty($post['o_club'])){
            $obj->o_club = array();
            foreach($post['o_club'] as $item) {
                $obj->o_club[$item] = $item;
            }
            $obj->o_club = serialize($obj->o_club);
        }
        else {
            $obj->o_club = '';
        }
        
        $obj->o_o_clubs = $post['o_o_clubs'];
        $obj->income = $post['income'];
        $obj->o_education = $post['o_education'];
        
        /**** Bussiness Association ****/
        if(!empty($post['bation'])){
            $obj->bation = array();
            foreach($post['bation'] as $item) {
                $obj->bation[$item] = $item;
            }
            $obj->bation = serialize($obj->bation);
        }
        else {
            $obj->bation = '';
        }
        
        $profileModel->updateStepRegistration($obj);
        WrdHelper::updateSummaryPoint($user->id,date('Y'),date('m'));
        $profile =  WrdHelper::getUserProfile($user->id,'userid');
		$myPoint = WrdHelper::updatePointOfUser($profile->user_id,$profile->member_id,$profile->dob,$profile->f_name,$profile->l_name);
       
        $_SESSION[$user->id.'p'] = $myPoint;
    }
    
    private function checkCurrentStep($post)
    {
        if(
            isset($post['prefix']) && isset($post['year_birth']) && isset($post['month_birth']) && isset($post['day_birth']) && 
            isset($post['f_name']) && isset($post['l_name']) && isset($post['name_on_card']) && isset($post['nationality']) && 
            isset($post['country_code']) && isset($post['phone']) && isset($post['address']) && isset($post['country']) && 
            isset($post['city']) && isset($post['distric']) && isset($post['pick_up_at'])
        )   {
            return 1;
        }
        
        if(
            isset($post['status']) || isset($post['social']) || isset($post['website']) || isset($post['skype']) ||  
            isset($post['yahoo']) || isset($post['gtalk']) || isset($post['msn']) || isset($post['hobbies']) || 
            isset($post['other_hobbies']) || isset($post['own_car']) || isset($post['num_children']) || isset($post['weekend_action'])
        )   {
            return 2;
        }
        
        if(
            isset($post['job_prefix']) || isset($post['job']) || isset($post['o_job']) || isset($post['department']) ||  
            isset($post['company_name']) || isset($post['industry']) || isset($post['c_info']) || isset($post['c_addr']) || 
            isset($post['c_country']) || isset($post['c_city']) || isset($post['c_distric'])
        )   {
            return 3;
        }
        
        if(
            isset($post['education']) || isset($post['o_club']) || isset($post['o_o_clubs']) || isset($post['income']) ||  
            isset($post['bation'])
        )   {
            return 4;
        }
		
		return 1;
    }
    
    /*
     * Old version
     */
    public function registerNewAccount(){
        
        /******* Pre Init *******/
        $db = JFactory::getDbo();
        $mainframe = JFactory::getApplication();
        $user = JFactory::getUser();
        
        /******** Process post data ********/
        $requestData = JRequest::get('post');
        $requestData['created_date']     = (empty($requestData['created_date']))? date("Y-m-d H:i:s") : $requestData['created_date'] ;
        $requestData['modify_date']     = date("Y-m-d H:i:s");
           
           
        if(isset($requestData['year_birth'])&& isset($requestData['month_birth']) && isset($requestData['day_birth'] )){
            $year_birth =  $requestData['year_birth'] ;
            $month_birth = $requestData['month_birth'] ;
            $day_birth = $requestData['day_birth'] ;
            $requestData['dob'] =     "$year_birth-$month_birth-$day_birth" ;
            unset($requestData['year_birth']); unset($requestData['month_birth']); unset($requestData['day_birth']);
        }
        
        if(!isset($requestData['o_source'])){
            unset($requestData['o_source']) ;
        }
        
        if(!isset($requestData['check_o_a_weekend'])){
            $requestData['o_a_weekend'] = '' ;
        }
        
        if($requestData['prefix'] == 'Prof.' || $requestData['prefix'] == 'Dr.' || $requestData['prefix'] == 'Mr.')
        	$requestData['gender'] = 'male' ;
        else
        	$requestData['gender'] = 'female' ;
        
        $model    = JModelLegacy::getInstance('profile','WrdModel');
        
        $requestData['step'] = 1;
        $requestData['u_name'] = $requestData['email1'];
        $requestData['u_pass'] = $requestData['password1'] ;
        $requestData['member_id'] = $requestData['u_name'] ;
        $data    = $model->register($requestData,1);
		
        if(!empty($data)){
        	$lang =& JFactory::getLanguage();
        	if($lang->getTag() == 'vi-VN')
        		$mainframe->redirect('index.php?option=com_content&view=article&layout=edit&id=96');
        	else 
        		$mainframe->redirect('index.php?option=com_content&view=article&layout=edit&id=6');
        }

        // Check for errors.
        if ($data === false) {
            // Save the data in the session.
            $mainframe->setUserState('com_wrd.profile.data', $requestData);
        
            // Redirect back to the edit screen.
            $this->setMessage(JText::sprintf('COM_USERS_REGISTRATION_SAVE_FAILED', $model->getError()), 'warning');
            $this->setRedirect(WrdHelperRoute::getProfileRoute());
            return false;
        }
        
        if($user->id != 0){
            $this->setMessage(JText::_('Saved'));
            $this->setRedirect(WrdHelperRoute::getProfileRoute());
        }else{
            // Redirect to the profile screen.
            if ($data === 'adminactivate'){
                $this->setMessage(JText::_('COM_USERS_REGISTRATION_COMPLETE_VERIFY'));
                $this->setRedirect(WrdHelperRoute::getProfileLoginRoute());
            } else if ($data === 'useractivate') {
                $this->setMessage(JText::_('COM_USERS_REGISTRATION_COMPLETE_ACTIVATE'));
                $this->setRedirect(WrdHelperRoute::getProfileLoginRoute());
            } else {
                $this->setMessage(JText::_('COM_USERS_REGISTRATION_SAVE_SUCCESS'));
                $this->setRedirect(WrdHelperRoute::getProfileLoginRoute());
            }
        }
        return true;
    }
    
    public function generateMemberId(){
        
		$db = JFactory::getDBO();
        $query_lucky = 'SELECT number FROM #__wrd_lucky_num WHERE `published`=1 and `available`=1';
        $db->setQuery($query_lucky);
        $rs_lucky = $db->loadResultArray();
        $query = 'SELECT member_id FROM #__wrd_profile ' ;
        $query.= ' WHERE member_id NOT IN (SELECT number FROM #__wrd_lucky_num WHERE `published`=1 and `available`=1)';        
        $query.= ' ORDER BY member_id DESC LIMIT 1';
        $db->setQuery($query);
        $rs = $db->loadObject();
        $code = $rs->member_id + 1;
        
        $tmparr = $rs_lucky;
        $total = count($tmparr)*2 ;
        for($i = 0 ; $i <= $total ; $i++){
            $tmparr[] = $code + $i ;
        }
		
        $tmparr = array_unique($tmparr,SORT_NUMERIC) ;
        sort($tmparr) ;
        //echo '<pre>';print_r($tmparr);exit;
		foreach ($tmparr as $val){
            if(in_array($val, $rs_lucky)){
			
                continue;
            }else{
                $code = $val;
                break;
            }
        }
        //echo $code;exit();
		return $code ;
        jexit();
    }
    
    public function reset(){
        $mainframe = JFactory::getApplication();
        echo 'todo';
        exit();
    }
    
    public function login(){

    	$ajax = JRequest::getInt('ajax');
        $app = JFactory::getApplication();
        // Populate the data array:
        $data = array();
        $data['username'] = JRequest::getVar('username', '', 'method', 'username');
        $data['password'] = JRequest::getString('password', '', 'post', JREQUEST_ALLOWRAW);
       
        $model    = $this->getModel('profile');
        
        $avalable = $model->checkUser('',$data['username']);
        
        // Get the log in options.
        $options = array();
        $options['remember'] = JRequest::getBool('remember', false);
        $options['return'] = '';
        
        // Get the log in credentials.
        $credentials = array();
        $credentials['username'] = $data['username'];
        $credentials['password'] = $data['password'];
        
        if(WrdHelper::isEmail($credentials['username'])){
        	$credentials['username'] = $this->convertEmailtoVIp($credentials['username']);
        }

        // Perform the log in.
        $error = $app->login($credentials,$options);
		$user = JFactory::getUser();
		$profile = WrdHelper::getUserProfile($user->id);
		
        // Check if the log in succeeded.
        if ($error === true) {
        	if($ajax == 1){
        		
        		$user= &JFactory::getUser();
        		
        		
        		//check complete profile
        		$db = &JFactory::getDbo();
        		$query = 'SELECT id FROM #__wrd_log_register WHERE id = '.$user->id;
        		$logged_data = $db->setQuery($query)->loadObject()->id;
        		
        		$myPoint = WrdHelper::getPointsofUser($user->id);
        		
				
        		if(intval($logged_data) == 0 && $myPoint == 0)
        			$data['redirect'] = 1;
				else
					$data['redirect'] = 0;

        		$_SESSION[$user->id.'p'] = $myPoint;

        		$return = '<li class="logged_in"><i class="fa fa-user"></i>'.'<a href="'.JRoute::_('index.php?option=com_wrd&view=profile&layout=default&id=1:my-account&Itemid=170').'"> '. $profile->f_name. '</a></li>';
        		
        		//$return .= '<li class="space" id="space"><a href="#">Space</a></li>';
        		
        		$return .= '<li class="logged_in logged_in_point"><i class="fa fa-trophy"></i><a href="'.JRoute::_('index.php?option=com_wrd&view=profile&layout=default&id=1:my-account&Itemid=170').'">'. number_format($myPoint,0,'.',',') .'</a> '.JText::_('WMC_TOP_MENU_POINT').'</li>';
        		
        		$return  .= '<li class="logged_in log_out"><i class="fa fa-sign-out"></i><a href="'.JRoute::_('index.php?option=com_wrd&task=profile.logout').'">'.JText::_('WMC_TOP_MENU_LOGOUT').'</a></li>';
        		
        		
        		$data['status'] = 'success';
        		$data['msg'] = $return;

        		echo json_encode($data);
        		jexit();
        	}
        	
            $user = JFactory::getUser();
            
            $app->setUserState('wrd.profile.login.form.data', array());
            
            if($profile->step > 4 || $profile->step > 1){
                //go to my account
               
                $app->redirect('index.php?option=com_wrd&view=profile&layout=default&id=1:my-account');
            }
            else{
            	
            	// go to complete profile
                //$app->redirect(WrdHelperRoute::getProfileRoute());
            	$app->redirect(JRoute::_('index.php?option=com_wrd&view=profile&layout=default&id=1&Itemid=170'));
            }
        } else {
        	
        	
        	if($ajax == 1){
        		$data['status'] = 'error';
        		$data['msg'] = JText::_('WRD_LOGIN_MSG_TRY_AGAIN');

        		echo json_encode($data);
        		jexit();
        	}
        	
            $app->setUserState('wrd.profile.login.form.data', array());
            $app->redirect(WrdHelperRoute::getProfileLoginRoute());
        }
    }

    function loginMobile(){
        $app = JFactory::getApplication();
        // Populate the data array:
        $data = array();
        $data['username'] = JRequest::getVar('username', '', 'method', 'username');
        $data['password'] = JRequest::getString('password', '', 'post', JREQUEST_ALLOWRAW);
        
        $model    = $this->getModel('profile');

        $options = array();
        $options['remember'] = JRequest::getBool('remember', false);
        $options['return'] = '';
        
        // Get the log in credentials.
        $credentials = array();
        $credentials['username'] = $data['username'];
        $credentials['password'] = $data['password'];
        
        if(WrdHelper::isEmail($credentials['username'])){
            $credentials['username'] = $this->convertEmailtoVIp($credentials['username']);
        }

        $error = $app->login($credentials,$options);
        $user = JFactory::getUser();
        $profile = WrdHelper::getUserProfile($user->id);
        
        if ($error === true) {
            
        }
        else{
            
        }
    }

    //check username or vipnumber available
     function checkInputUserName(){
     	
    	$ajax = JRequest::getInt('ajax');

		if($ajax == 1){
			$credentials['username'] = JRequest::getVar('email');
			if($credentials['username'] == ''){
				$credentials['username'] = JRequest::getVar('username');
				
				$data['status'] = 'error';
				$data['msg'] = JText::_('JS_ALERT_PLEASE_INPUT_USERNAME');
					
				echo json_encode($data);
				jexit();	
			}

			if(!is_numeric($credentials['username'])){
				if(!WrdHelper::isEmail($credentials['username']))
				{
					$data['status'] = 'error';
					$data['msg'] = $credentials['username'] .' '. JText::_('JS_ALERT_IS_NOT_MATCH');
					
					echo json_encode($data);
					jexit();
				}
			}
		}
		
		
        $db = &JFactory::getDbo();
       	$query = "SELECT username FROM #__users WHERE username = ".$db->Quote($credentials['username'])." OR email =".$db->Quote($credentials['username']) ;

       	$db->setQuery($query);
       	$result = $db->loadObject();
       	if($ajax == 1)
       	{

       		if($result->username == '')
       		{
       			$data['status'] = 'error';
       			$data['msg'] =  JText::_('WRD_LOGIN_MSG_EMAIL_OR_VIP_IS_INVALID');
       		}
       		else{
       			$data['username'] = $result->username;
       			$data['status'] = 'success';
       			$data['msg'] = '';
       		}
       		
       		echo json_encode($data);
       		jexit();
       	}
       
        return $result->username; 
    }
    
    //checkpassword
    public function checkpass(){
    	$ajax 		= JRequest::getInt('ajax');
    	if($ajax != 1) return false;
    	
    	$pass 		= JRequest::getVar('password');
    	$username 	= JRequest::getVar('username');

    	$db    = JFactory::getDbo();
    	$query = $db->getQuery(true)
    	->select('id, password')
    	->from('#__users')
    	->where('username=' . $db->quote($username));
    	
    	$db->setQuery($query);
    	$result = $db->loadObject();
    	
    	if ($result)
    	{
	    	$isvalid = JUserHelper::verifyPassword($pass, $result->password, $result->id);
	
			if($isvalid === true){
				$data['status'] = 'success';
				$data['msg'] = '';
			}else{
				$data['status'] = 'error';
				$data['msg'] = JText::_('WRD_LOGIN_MSG_WRONG_PASS');
			}
    	}else{
    		$data['status'] = 'error';
    		$data['msg'] = JText::_('WRD_LOGIN_MSG_WRONG_PASS');
    	}
    	
		echo json_encode($data);
		jexit();

    }
    
    function changepass(){
    	$app = JFactory::getApplication('site');
    	$user= JFactory::getUser();
    	$post = JRequest::get('post');

    	$db = &JFactory::getDbo();
    	$query = 'SELECT password FROM #__users WHERE id='.$user->id.' AND password  LIKE "%'.md5($post['cpass']).'%"';
    	
    	$db->setQuery($query);
    	$rs = $db->loadObject();
    	
    	if($rs->password == ''){
    		$app->redirect(JRoute::_('index.php?option=com_wrd&view=profile&layout=reset&id=0:change-password&Itemid=119&lang=vi',false),JText::_('WRD_RESET_PASSWORD_WRONG'));
    	}else{
    		if($post['npass'] == $post['npassr']){
    			$query = 'UPDATE #__users SET password = "'.md5($post['npass']).'" WHERE id ='.$user->id;
    			$db->setQuery($query)->query();
    			$app->redirect('index.php');
    		}
    	}
    }
    
    
    //logout
    public function logout(){
        
        $app = JFactory::getApplication();
        $error = $app->logout();

        if ($error === true) {
            $app->redirect('index.php', false);
        } else {
            $app->redirect(WrdHelperRoute::getProfileRoute());
        }
    } 
    
    public function forgot(){
        
    }
    
    public function addLogs(){
        $mainframe = JFactory::getApplication();
        
    }

    public function request()
    {
        // Check the request token.
        JRequest::checkToken('post') or jexit(JText::_('JINVALID_TOKEN'));

        $app    = JFactory::getApplication();
        $model    = $this->getModel('profile');
        $data    = JRequest::getVar('username','','post','','');
    
        // Submit the password reset request.
        $return    = $model->processResetRequest($data);

        // Check for a hard error.
        if (JError::isError($return)) {
            // Get the error message to display.
            if ($app->getCfg('error_reporting')) {
                $message = $return->getMessage();
            } else {
                $message = JText::_('COM_USERS_RESET_REQUEST_ERROR');
            }
            $route    = 'index.php?option=com_wrd&view=profile';
            // Go back to the request form.
            $this->setRedirect(JRoute::_($route, false), $message, 'error');
            return false;
        } elseif ($return === false) {
            
            $route    = 'index.php?option=com_wrd&view=profile';
            // Go back to the request form.
            $message = JText::sprintf('COM_USERS_RESET_REQUEST_FAILED', $model->getError());
            $this->setRedirect(JRoute::_($route, false), $message, 'notice');
            return false;
        } else {
            $route    = 'index.php?option=com_wrd&view=profile&layout=confirm';
            // Proceed to step two.
            $this->setRedirect(JRoute::_($route, false), $message);
            return true;
        }
    }

    function confirm()
    {
        // Check the request token.
        JRequest::checkToken('request') or jexit(JText::_('JINVALID_TOKEN'));

        $app    = JFactory::getApplication();
        $model    = $this->getModel('profile');
        $data['username']    = JRequest::getVar('username','','post','','');
        $data['token']    = JRequest::getVar('verification_code','','post','','');

        // Confirm the password reset request.
        $return    = $model->processResetConfirm($data);
        // Check for a hard error.
        if (JError::isError($return))
        {
            // Get the error message to display.
            if ($app->getCfg('error_reporting')) {
                $message = $return->getMessage();
            } else {
                $message = JText::_('COM_USERS_RESET_CONFIRM_ERROR');
            }

            // Get the route to the next page.
            $route    = 'index.php?option=com_wrd&view=profile&layout=confirm';

            // Go back to the confirm form.
            $this->setRedirect(JRoute::_($route, false), $message, 'error');
            return false;
        } elseif ($return === false) {
            // Confirm failed.
            // Get the route to the next page.
            $route    = 'index.php?option=com_wrd&view=profile&layout=confirm';

            // Go back to the confirm form.
            $message = JText::sprintf('COM_USERS_RESET_CONFIRM_FAILED', $model->getError());
            $this->setRedirect(JRoute::_($route, false), $message, 'notice');
            return false;
        } else {
            // Confirm succeeded.
            // Get the route to the next page.
            $route    = 'index.php?option=com_wrd&view=profile&layout=complete';

            // Proceed to step three.
            $this->setRedirect(JRoute::_($route, false));
            return true;
        }
    }
    public function complete()
    {
        // Check for request forgeries
        JRequest::checkToken('post') or jexit(JText::_('JINVALID_TOKEN'));

        $app    = JFactory::getApplication();
        $model    = $this->getModel('profile');        
        $data['password1']    = JRequest::getVar('password','','post','','');
        $data['password2']    = JRequest::getVar('password_confirm','','post','','');
        if($data['password1']!=$data['password2']){
            $message = "Completing reset password failed: The passwords you entered do not match. Please enter your desired password in the password field and confirm your entry by entering it in the confirm password field.";
            $route    = 'index.php?option=com_wrd&view=profile&layout=complete';
            $this->setRedirect(JRoute::_($route, false), $message, 'error');
        }else{
        // Complete the password reset request.
        $return    = $model->processResetComplete($data);

        // Check for a hard error.
        if (JError::isError($return)) {
            // Get the error message to display.
            if ($app->getCfg('error_reporting')) {
                $message = $return->getMessage();
            } else {
                $message = JText::_('COM_USERS_RESET_COMPLETE_ERROR');
            }

            // Get the route to the next page.
            //$itemid = UsersHelperRoute::getResetRoute();
            //$itemid = $itemid !== null ? '&Itemid='.$itemid : '';
            $route    = 'index.php?option=com_wrd&view=profile&layout=complete';

            // Go back to the complete form.
            $this->setRedirect(JRoute::_($route, false), $message, 'error');
            return false;
        } elseif ($return === false) {
            $route    = 'index.php?option=com_wrd&view=profile&layout=complete';

            // Go back to the complete form.
            $message = JText::sprintf('COM_USERS_RESET_COMPLETE_FAILED', $model->getError());
            $this->setRedirect(JRoute::_($route, false), $message, 'notice');
            return false;
        } else {
            $route    = 'index.php#login';
            // Proceed to the login form.
            $message = JText::_('COM_USERS_RESET_COMPLETE_SUCCESS');
            $this->setRedirect(JRoute::_($route, false), $message);
            return true;
        }
        }
    }
    
    public function view_activity(){
        $app = JFactory::getApplication() ;
        $post = JRequest::get('post') ;
        $month     = empty($post['month']) ? 0 : $post['month'] ; 
        $year   = empty($post['year']) ? 0 : $post['year'] ;
        
        $link = 'index.php?option=com_wrd&view=profile&layout=finish' ;
        if(!empty($month)){
            $link .= '&month='.$month ; 
        }
        if(!empty($year)){
            $link .= '&year='.$year ;
        }
        $link .= '&Itemid=119' ;
        $app->redirect($link);
        exit();
    }
    
    public function convertEmailtoVIp($email){
    	$db = &JFactory::getDbo();
    	$query = 'SELECT username FROM #__users WHERE email = "'.$email.'"';
    	return $db->setQuery($query)->loadObject()->username;
    }
    
    function checkCompany($name){
    	$db = JFactory::getDbo();
    	$query = 'SELECT * FROM `#__wrd_companyname` where `name` = '.$db->quote($name);
    	$rs = $db->setQuery($query)->loadObject()->name;

    	if($rs == ''){
    		$obj = new stdClass();
    		$obj->id = null;
    		$obj->name = $name;
    		$obj->address = '';
    		$obj->logo = '';
    		$obj->created_date = '0000-00-00 00:00:00';
    		$obj->created_by = 0;
    		$obj->modified_date = '0000-00-00 00:00:00';
    		$obj->modified_by = 0;
    		$obj->published = 1;
    		$obj->ordering = 0;
    		$db->insertObject('#__wrd_companyname', $obj);
    	}
    }

	function sendEmailNoticeWhenUserChangeProfile($post){
		
		WrdHelper::sendEmailNoticeWhenChangeProfile($post,$post['profile'],$fontEnd = true);
		
	}

	function getValueOfDropdown($key,$value){
		$db = &JFactory::getDbo();
		switch ($key) {
			case 'nationality':
				$query = 'SELECT name FROM #__wrd_country WHERE id ='.$value;
				$rs = $db->setQuery($query)->loadObject()->name;
				break;
			case 'country':
				$query = 'SELECT name FROM #__wrd_country WHERE id ='.$value;
				$rs = $db->setQuery($query)->loadObject()->name;
				break;
			case 'city':
				$query = 'SELECT name FROM #__wrd_city WHERE id ='.$value;
				$rs = $db->setQuery($query)->loadObject()->name;
				break;
			case 'distric':
				$query = 'SELECT name FROM #__wrd_distric WHERE id ='.$value;
				$rs = $db->setQuery($query)->loadObject()->name;
				break;
			case 'pick_up_at':
				$query = 'SELECT name FROM #__wrd_outlets WHERE code ="'.$value.'"';
				$rs = $db->setQuery($query)->loadObject()->name;
				break;	
			case 'lprefer':
				$query = 'SELECT name FROM #__wrd_lprefer WHERE id ='.$value;
				$rs = $db->setQuery($query)->loadObject()->name;
				break;	
			default:
				
				break;
		}
		
		return $rs;
	}
}